﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using HuoTu.Common;
using DomainSearchTools.Common;
using log4net;
using System.Threading;

namespace DomainSearchTools
{
    public partial class Main : Form
    {
        private static ILog logger = LogManager.GetLogger(typeof(Main));
        /// <summary>
        /// 当前页面的搜索结果
        /// </summary>
        private static class Result
        {
            /// <summary>
            /// 已显示的总数量（注册与未注册）
            /// </summary>
            public static int TotalCount = 0;
            /// <summary>
            /// 未注册数量
            /// </summary>
            public static int NoRegisterCount = 0;
            /// <summary>
            /// 注册数量
            /// </summary>
            public static int RegisterCount = 0;
            /// <summary>
            /// 域名搜索类（监控搜索类的情况）
            /// </summary>
            public static DomainSearchHelper Search = null;
            /// <summary>
            /// 域名推入类
            /// </summary>
            public static DomainPushHelper Push = null;

            /// <summary>
            /// 搜索类的监控时间
            /// </summary>
            public static System.Windows.Forms.Timer Time = new System.Windows.Forms.Timer()
            {
                Interval = 200,
                Enabled = false
            };

            public static void Clear()
            {
                TotalCount = 0;
                NoRegisterCount = 0;
                RegisterCount = 0;
                Search = null;
                Push = null;
            }

        }

        #region 页面初始化
        public Main()
        {
            InitializeComponent();
        }

        private void Main_Load(object sender, EventArgs e)
        {
            cmbPrevMode.DataSource = SysEnum.Enum2List<SearchMode>();
            cmbPrevMode.DisplayMember = "Description";
            cmbPrevMode.ValueMember = "Value";

            clbSuffix.DataSource = Config.suffix.Split(',');
            clbSuffix.SetItemChecked(0, true);
            ShowSuffix();
            clbSuffix.Visible = false;

            plToFile.Visible = false;

            cbDomainSuffix.DataSource = Config.suffix.Split(',');
        }

        private void Main_Click(object sender, EventArgs e)
        {
            plToFile.Visible = false;
            clbSuffix.Visible = false;
        }
        #endregion

        #region 域名类型选择
        private void txtSuffix_Click(object sender, EventArgs e)
        {
            clbSuffix.Visible = true;
        }

        private void txtSuffix_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = true;
        }

        private void ShowSuffix()
        {
            string result = "";
            foreach (int index in clbSuffix.CheckedIndices)
            {
                result += clbSuffix.Items[index].ToString() + ",";
            }
            result = result.Length > 0 ? result.Substring(0, result.Length - 1) : "";
            txtSuffix.Text = result;
        }

        private void clbSuffix_SelectedValueChanged(object sender, EventArgs e)
        {
            ShowSuffix();
            //ListControl lc = (ListControl)sender;
            //if (clbSuffix.CheckedIndices.Count == 1 && clbSuffix.GetItemChecked(lc.SelectedIndex))
            //    return;

            //clbSuffix.SetItemChecked(lc.SelectedIndex, !clbSuffix.GetItemChecked(lc.SelectedIndex));
        }
        #endregion

        #region 搜索域名注册情况
        /// <summary>
        /// 开始搜索
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGo_Click(object sender, EventArgs e)
        {
            //搜索条件 待处理
            if (txtSuffix.Text == "")
            {
                txtSuffix.Focus();
                MessageBox.Show("请选择域名类型");
                return;
            }


            btnGo.Enabled = false;
            btnStop.Enabled = true;
            //清空上次搜索的结果
            DomainPoolHelper.Clear();
            DomainSearchPoolHelper.Clear();
            Result.Clear();
            lvRegister.Items.Clear();
            lvNoRegister.Items.Clear();

            //准备搜索条件
            string prevBegin = txtPrevBegin.Text.Trim();
            SearchMode mode = (SearchMode)cmbPrevMode.SelectedValue;
            string prevEnd = txtPrevEnd.Text.Trim();
            string[] suffix = txtSuffix.Text.Split(',');

            //根据搜索条件 向池中推入数据
            DomainPushHelper push = new DomainPushHelper(prevBegin, mode, prevEnd, suffix);
            push.PushSpeed = 100;
            push.StartPush();

            //启动搜索服务
            DomainSearchHelper search = new DomainSearchHelper();
            search.Time.Interval = 100;
            search.StartSearch();

            //监控搜索并显示数据
            Result.Push = push;
            Result.Search = search;
            Result.Time.Tick += Time_Tick;
            Result.Time.Enabled = true;
        }

        void Time_Tick(object sender, EventArgs e)
        {
            //搜索并显示完毕
            if (Result.Push.Status == PushStatus.FINISHED && Result.TotalCount == DomainPoolHelper.List.Count)
            {
                StopSearch();
                MessageBox.Show("finished");
            }

            //System.Timers.Timer tt = (System.Timers.Timer)sender;
            //tt.Stop();
            ShowResult();
            //tt.Enabled = true;
        }

        private void ShowResult()
        {
            txtPrevBegin.Text = DomainPoolHelper.List.Count.ToString()
                + " " + DomainSearchPoolHelper.List.Count.ToString()
                + " " + Result.TotalCount;
            //对比搜索数量显示注册数据
            if (Result.TotalCount < DomainSearchPoolHelper.List.Count)
            {
                for (int i = Result.TotalCount; i < DomainSearchPoolHelper.List.Count; i++)
                {
                    DomainPoolModel model = DomainSearchPoolHelper.List[i];
                    if (model.Status == DomainStatus.NOREGED)
                    {
                        Result.NoRegisterCount++;
                        ListViewItem row = new ListViewItem();
                        row.SubItems[0].Text = Result.NoRegisterCount.ToString();
                        row.SubItems.Add(model.DomainName);
                        lvNoRegister.Items.Add(row);
                    }
                    else if (model.Status == DomainStatus.REGED)
                    {
                        Result.RegisterCount++;
                        ListViewItem row = new ListViewItem();
                        row.SubItems[0].Text = Result.RegisterCount.ToString();
                        row.SubItems.Add(model.DomainName);
                        lvRegister.Items.Add(row);
                    }
                    Result.TotalCount++;
                }
            }
            tabResultNoReg.Text = string.Format(@"未被注册的域名列表（{0}个）", Result.NoRegisterCount);
            tabResultReg.Text = string.Format(@"被注册的域名列表（{0}个）", Result.RegisterCount);
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            StopSearch();
        }

        private void StopSearch()
        {
            btnGo.Enabled = true;
            btnStop.Enabled = false;

            Result.Push.StopPush();
            if (Result.Search.Time != null) Result.Search.Time.Enabled = false;
            if (Result.Time != null) Result.Time.Enabled = false;
        }
        #endregion

        #region 域名注册情况搜索结果导出文件
        /// <summary>
        /// 需要导出的域名状态
        /// </summary>
        private DomainStatus exportDomainStatus = DomainStatus.NOREGED;
        /// <summary>
        /// 导出未注册的内容
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExportNoRegister_Click(object sender, EventArgs e)
        {
            exportDomainStatus = DomainStatus.NOREGED;
            plToFile.Visible = true;
        }

        /// <summary>
        /// 导出已注册的内容
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExportRegister_Click(object sender, EventArgs e)
        {
            exportDomainStatus = DomainStatus.REGED;
            plToFile.Visible = true;
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            ExportFileType fileType = ExportFileType.TXT;
            if (rdbToXlsFile.Checked) fileType = ExportFileType.XLS;

            SaveFileDialog dialog = new SaveFileDialog();     //显示选择文件对话框
            dialog.InitialDirectory = "D:\\";
            if (fileType == ExportFileType.TXT)
                dialog.Filter = "txt files (*.txt)|*.txt";
            else if (fileType == ExportFileType.XLS)
                dialog.Filter = "xls files (*.xls;*.xlsx)|*.xls;*.xlsx";
            dialog.FilterIndex = 2;
            dialog.RestoreDirectory = true;

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                List<string> list = new List<string>();

                ListView view = null;
                if (exportDomainStatus == DomainStatus.NOREGED) view = lvNoRegister;
                else if (exportDomainStatus == DomainStatus.REGED) view = lvRegister;

                foreach (ListViewItem item in view.Items) list.Add(item.SubItems[1].Text);

                DomainFileHelper df = new DomainFileHelper();
                string error = "";
                if (df.SaveToFile(list, fileType, dialog.FileName, ref error))
                {
                    plToFile.Visible = false;
                    MessageBox.Show("保存成功");
                }
                else
                {
                    MessageBox.Show(error);
                }

            }

            //if (this.folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            //{
            //    if (this.folderBrowserDialog1.SelectedPath.Trim() != "")
            //        this.textBox4.Text = this.folderBrowserDialog1.SelectedPath.Trim();
            //}
        }
        #endregion

        #region 域名详细信息
        /// <summary>
        /// 查询域名注册信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearchDomainInfo_Click(object sender, EventArgs e)
        {
            string name = txtDomain.Text;
            string suffix = cbDomainSuffix.SelectedValue.ToString();
            string domainName = name + suffix;
            DoSearchDomainInfo(domainName);
        }

        private void lvRegister_SelectedIndexChanged(object sender, EventArgs e)
        {
            ListViewItem list = lvRegister.FocusedItem;
            if (list != null)
            {
                string domainName = list.SubItems[1].Text;
                string prevName = SysDomain.GetPrev(domainName);
                string suffix = SysDomain.GetSuffix(domainName);

                txtDomain.Text = prevName;

                int index = cbDomainSuffix.FindString(suffix);
                cbDomainSuffix.SelectedIndex = index;
                //cbDomainSuffix.SelectedValue = suffix;
             

                DoSearchDomainInfo(domainName);
            }
        }

        private void DoSearchDomainInfo(string domainName)
        {
            if (!SysDomain.IsRegDomain(domainName))
            {
                MessageBox.Show("不符合域名规则");
                return;
            }
            string suffix = SysDomain.GetSuffix(domainName);

            SearchDomainWhois s = new SearchDomainWhois(domainName, suffix);
            Thread thread = new Thread(new ThreadStart(s.Search));
            thread.Start();
            thread.Join();

            txtDomainInfo.Text = s.Result;
        }
       
        #endregion

    }

    /// <summary>
    /// 查询域名注册信息
    /// </summary>
    public class SearchDomainWhois
    {
        private string domainName;
        private string suffix;

        private string result;

        public string Result
        {
            get { return result; }
            set { result = value; }
        }

        public SearchDomainWhois(string domainName, string suffix)
        {
            this.domainName = domainName;
            this.suffix = suffix;
        }

        public void Search()
        {
            try
            {
                //string suffix = cbxSuffix.SelectedValue.ToString();
                //{
                //A.socket形式发送数据
                int port = 43;
                string server = WhoisServer.GetServer(suffix);

                string content = string.Format(@"{0} {1}
", WhoisCommand.domain, domainName);

                SocketHelper socket = new SocketHelper();
                string response = socket.Send(server, port, content);
                //解析数据并显示
                string info = WhoisInfo.Parse(response);
                result = info;

                //B.Tcp的形式，发送到服务器并接收数据(内部测试)
                //client = new TcpClient();
                //int port = 234;
                //string ip = "127.0.0.1";
                //string content = string.Format(@"whois www.baidu.com");
                //SocketHelper.TcpSend(ip, port, content);
                //}
                //MessageBox.Show("完成");
            }
            catch (Exception ex)
            {
                result = "暂未查询到注册信息";
            }
        }
        
    }
}